<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/13/013
 * Time: 9:16
 */

namespace app\api\controller;


use think\Controller;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class Project extends Controller
{

    function html2text($str){
        $str = preg_replace("/<style .*?<\\/style>/is", "", $str);
        $str = preg_replace("/<script .*?<\\/script>/is", "", $str);
        $str = preg_replace("/<br \\s*\\/>/i", "", $str);
        $str = preg_replace("/<\\/?p>/i", "", $str);
        $str = preg_replace("/<\\/?td>/i", "", $str);
        $str = preg_replace("/<\\/?div>/i", "", $str);
        $str = preg_replace("/<\\/?blockquote>/i", "", $str);
        $str = preg_replace("/<\\/?li>/i", "", $str);
        $str = preg_replace("/ /i", " ", $str);
        $str = preg_replace("/ /i", " ", $str);
        $str = preg_replace("/&/i", "&", $str);
        $str = preg_replace("/&/i", "&", $str);
        $str = preg_replace("/</i", "<", $str);
        $str = preg_replace("/</i", "<", $str);
        $str = preg_replace("/“/i", '"', $str);
        $str = preg_replace("/&ldquo/i", '"', $str);
        $str = preg_replace("/‘/i", "'", $str);
        $str = preg_replace("/&lsquo/i", "'", $str);
        $str = preg_replace("/'/i", "'", $str);
        $str = preg_replace("/&rsquo/i", "'", $str);
        $str = preg_replace("/>/i", ">", $str);
        $str = preg_replace("/>/i", ">", $str);
        $str = preg_replace("/”/i", '"', $str);
        $str = preg_replace("/&rdquo/i", '"', $str);
        $str = strip_tags($str);
        $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
        $str = preg_replace("/&#.*?;/i", "", $str);
        return $str;
    }


    public function iflogin(){
        $project_user = Session::get("project_user");
        if(empty($project_user)){
            $black['code'] = 1;
            $black['msg'] = "请重新登录";
            echo json_encode($black);die;
        }
        return $project_user;
    }


    /**
     * 筛选条件
     */
    public function screenApi(){
        $progress = [['value'=>1,'title'=>"已完成"],['value'=>2,'title'=>"未完成"]];
        $comment = [['value'=>1,'title'=>"已点评"],['value'=>2,'title'=>"未点评"]];
        $project_status = [['value'=>1,'title'=>"正常"],['value'=>2,'title'=>"逾期"]];
        $pro_type = $this->dictionary("project_type",$_POST['appid']);
        $type = [];
        foreach ($pro_type as $v){
            $type[] = $v;
        }
        $black['code'] = 0;
        $black['progress'] = $progress;
        $black['comment'] = $comment;
        $black['project_status'] = $project_status;
        $black['type'] = $type;
        return json_encode($black);
    }


    /**
     * 数据字典，查询字典
     * @param $keword
     * @return mixed
     */
    public function dictionary($keword,$appid){
        $config = Db::name("config")->where(['xcx_appid' => $appid])->find();
        $where['uniacid'] = $config['id'];
        $where['status'] = 1;
        $black = Db::name($keword)->where($where)->field("id,name")->select();
        $data = [];
        foreach ($black as $k=>$v){
            $data[] = ['value'=>$v['id'],'title'=>$v['name']];
        }
        return $data;
    }


    /**
     * 查询我负责的项目
     * @param $name
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function conscientious($name){
        $where = "(duty_person like '%".$name."%') and status=1";
        $pro = Db::name("project_pro")->where($where)->field("id")->select();
        $pro_v = empty($pro)?[0]:array_column($pro,'id');
        return $pro_v;
    }


    /**
     * 查询我关联的项目
     * @param $uid
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function associated($uid){
        //已关联项目
        $proWhere['account_id'] = $uid;
        $project_id = Db::name("project_account_pro")->where($proWhere)->field("project_id")->select();
        $project_id = empty($project_id)?[0]:array_column($project_id,'project_id');
//        $project_ids = implode($project_id,",");
//        if(empty($project_ids)){
//            $project_ids = [0];
//        }
        return $project_id;
    }

    /**
     * 项目投资金额
     */
    public function investment(){

        try{
            if(empty($_POST['appid'])){throw new Exception("appid不能为空");}
            $appid = $_POST['appid'];
            $config = Db::name("config")->where(['xcx_appid' => $appid])->find();

            //当前年
//            $year = empty($_POST['year'])?date("Y",time()):$_POST['year'];
            //查询本年总投资
//            $where['onstream_time'] = ['like',"%{$year}%"];
            $where['status'] = 1;
            $where['uniacid'] = $config['id'];
            $investment = Db::name("project_pro")->where($where)->sum("investment");
            $investment = $investment;

            //本年度计划投资
//            $where1['a.plan_title'] = $year;
            $where1['b.status'] = 1;
            $where1['b.uniacid'] = $config['id'];
            $plan_investment = Db::name("project_pro_plan")->alias('a')
                ->join("project_pro b","a.pro_id = b.id")->where($where1)->order("a.id desc")->sum("plan_investment");
            $plan_investment = $plan_investment;


//            if(!empty($_POST['year']) & $_POST['year']!=2021){
//                $investment = 0;
//                $plan_investment = 0;
//            }

            $black['code'] = 0;
            $black['msg'] = "查询成功";
            $black['investment'] = $investment;
            $black['investmentcount'] = $investment*2;
            $black['plan_investment'] = $plan_investment;
            $black['plan_investmentcount'] = $plan_investment*2;
//            $black['procount'] = $procount;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    /**
     * 项目投资数量
     */
    public function projectCount(){

        try{
            if(empty($_POST['appid'])){throw new Exception("appid不能为空");}
            $appid = $_POST['appid'];
            $config = Db::name("config")->where(['xcx_appid' => $appid])->find();

            //当前年
//            $year = empty($_POST['year'])?date("Y",time()):$_POST['year'];
            //项目数量
            $typeValue = [];

//            $where['onstream_time'] = ['like',"%{$year}%"];
            $where['status'] = 1;
            $where['uniacid'] = $config['id'];
            $procount = Db::name("project_pro")->where($where)->count("*");
//            $typeValue[] = ['name'=>'年度总项目','value'=>$procount];

            //查询字典
            $pro_type = $this->dictionary("project_type",$appid);
            $harmonious = 0;
            foreach ($pro_type as $k=>$v){
                $where['project_type'] = $v['value'];
                $pro_type[$k]['count'] = $count = Db::name("project_pro")->where($where)->count("*");
                $harmonious = $harmonious+$count;
                $typeValue[] = ['name'=>$v['title'],'value'=>$count];
            }
            $other = $procount - $harmonious;
//            $typeValue[] = ['name'=>'其他项目','value'=>$other];

            $black['code'] = 0;
            $black['msg'] = "查询成功";
            $black['typeValue'] = $typeValue;
            $black['count'] = $procount;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);

    }


    /**
     * 关联项目列表
     */
    public function listApi(){
        $common = new Common();

//        $project_user = $common->testusername();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            //判断是否有点评权限
            $commentAuto = Db::name("project_account")->where(['id'=>$project_user['id']])->value("comment");
            $page = empty($_POST['page'])?1:intval($_POST['page']);
            $limit = empty($_POST['limit'])?100:intval($_POST['limit']);
//            $limit = 100;
            $start = ($page - 1) * $limit;

            //已关联项目
            $proWhere['account_id'] = $project_user['id'];
            $project_id = Db::name("project_account_pro")->where($proWhere)->field("project_id")->select();

            if(!empty($project_id)){
                $project_id = array_column($project_id,'project_id');
                $project_ids = implode($project_id,",");
            }

            if(empty($project_ids)){
                $project_ids = 0;
            }
            //已关联项目end

            // or leader like '%".$name."%' 领导人查询
            $name = $project_user['name'];
            $where = "(id in (".$project_ids.") or duty_person like '%".$name."%') and status=1";

            //筛选
            if(!empty($_POST['comment'])){
                $where .=" and comment=".$_POST['comment'];
            }
            if(!empty($_POST['project_type'])){
                $where .=" and project_type=".$_POST['project_type'];
            }
            if(!empty($_POST['progress'])){
                $progress = $_POST['progress'];
                $nowtime = date('Y-m-d',time());
                if($progress==1){
                    $where .=" and plan_complete_time>='$nowtime'";
                }else{
                    $where .=" and plan_complete_time<'$nowtime'";
                }
            }

            if(!empty($_POST['complete'])){
                $complete = $_POST['complete'];
                if($complete==1){
                    $where .=" and progress=100 and project_status=0";
                }else{
                    $where .=" and progress<100 and project_status=0";
                }
            }



            if(!empty($_POST['keyword'])){
                $where .=" and (title like '%".$_POST['keyword']."%' or duty_unit like '%".$_POST['keyword']."%' or duty_person like '%".$_POST['keyword']."%') ";
            }

            if(!empty($_POST['myname'])){
                $where .=" and (duty_person like '%".$project_user['name']."%' or leader like '%".$project_user['name']."%')";
            }

            if(!empty($_POST['project_status'])){
                $project_status = $_POST['project_status']-1;
                $where .=" and project_status=".$project_status;
            }


            $list = Db::name("project_pro")->where($where)
                ->field("id,title,thumb,duty_person,leader,progress,year_progress,duty_unit,project_status,difficulty")
                ->limit($start,$limit)
                ->order("sort desc,id desc")->select();
            foreach ($list as $k=>$v){
                $list[$k]['difficulty'] = empty($v['difficulty'])?'':$v['difficulty'];
                $list[$k]['content'] = empty($v['difficulty'])?'':$v['difficulty'];
                $list[$k]['leading_cadre'] = 0;
                $list[$k]['comment'] = 0;
                $list[$k]['read'] = 0;
                $list[$k]['thumb'] = empty($v['thumb'])?'':$v['thumb'];
                if(in_array($v['id'],$project_id) & $commentAuto==1){
                    //判断是否已点评
                    $commentWhere['pro_id'] = $v['id'];
                    $commentWhere['add_id'] = $project_user['id'];
                    $comment = Db::name("project_pro_comment")->where($commentWhere)->value("id");
                    $list[$k]['comment'] = empty($comment)?1:2;
                }
                if(strpos($v['duty_person'],$project_user['name'])!==false){
                    //是否存在点评信息
                    $commentCount = Db::name("project_pro_comment")->where(['pro_id'=>$v['id']])->count("id");
                    //已读数
                    $readCount = Db::name("project_pro_comment_log")->where(['pro_id'=>$v['id'],'read_id'=>$project_user['id']])->count("id");
                    //是否存在未读信息
                    if($commentCount!=0){
                        $list[$k]['read'] = ($commentCount!=$readCount)?1:2;
                    }
                    $list[$k]['leading_cadre'] = 1;
                }
            }
            $count = Db::name("project_pro")->where($where)->count("*");
            $black['code'] = 0;
            $black['msg'] = "查询成功";
            $black['list'] = $list;
            $black['count'] = $count;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    /**
     * 获取项目详情
     */
    public function project_detail(){

        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }

        try{
            //查询项目基本信息
            $where['id'] = $_POST['id'];
            $detail = Db::name("project_pro")->where($where)
                ->field("id,title,thumb,duty_unit,duty_person,content,remark,onstream_time,plan_complete_time,complete_time,project_type,progress,year_progress,leader,investment,difficulty,project_chief,project_phone,contact_person,contact_phone")
                ->find();

            $detail['leading_cadre'] = 0;
            if(strpos($detail['duty_person'],$project_user['name'])!==false){
                $detail['leading_cadre'] = 1;
            }

            $detail['difficulty'] = empty($detail['difficulty'])?'':$detail['difficulty'];

            $detail['project_chief'] = empty($detail['project_chief'])?'':$detail['project_chief'];
            $detail['project_phone'] = empty($detail['project_phone'])?'':$detail['project_phone'];
            $detail['contact_person'] = empty($detail['contact_person'])?'':$detail['contact_person'];
            $detail['contact_phone'] = empty($detail['contact_phone'])?'':$detail['contact_phone'];
            //形象进度
//            $proWhere['pro_id'] = $detail['id'];
//            $figure = Db::name("project_pro_figure")->where($proWhere)->field("id,title,show_time,content,images")->order("id desc")->select();
//            foreach ($figure as $k=>$v){
//                $figure[$k]['images'] = explode(";",$v['images']);
//            }
//            //推进进度
//            $plan = Db::name("project_pro_plan")->where($proWhere)->field("id,plan_title,plan_investment,plan_content")->order("plan_title desc")->select();
//
//            //点评内容
//            $comment = Db::name("project_pro_comment")->where($proWhere)->field("id,content,images,addtime")->order("id desc")->select();
//            foreach ($comment as $k=>$v){
//                $comment[$k]['images'] = explode(";",$v['images']);
//                $comment[$k]['title'] = $detail['title'];
//                $comment[$k]['duty_unit'] = $detail['duty_unit'];
//            }

//            $detail['content'] = $this->html2text($detail['content']);
            $black['detail'] = $detail;
//            $black['figure'] = $figure;
//            $black['plan'] = $plan;
//            $black['comment'] = $comment;
            $black['code'] = 0;
            $black['msg'] = "查询成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    /**
     * 获取点评列表
     */
    public function pro_comment(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            //形象进度
            $proWhere['pro_id'] = $_POST['id'];
            $proWhere['pid'] = 0;
            $comment = Db::name("project_pro_comment")->where($proWhere)->field("id,content,images,addtime,add_id,pro_id,type")->order("id desc")->select();
            foreach ($comment as $k=>$v){
                $comment[$k]['reply_type'] = 0;

                //查询点评人信息
                $reviewer = Db::name("project_account")->where(['id'=>$v['add_id']])->value("name");
                $comment[$k]['reviewer'] = empty($reviewer)?"平台管理员":$reviewer;

                if($v['type'] == 1){
                    $comment[$k]['reviewer'] = Db::name("account")->where(['id'=>$v['add_id']])->value("account");
                }


                //责任领导
                $leader = Db::name("project_pro")->where(['id'=>$v['pro_id']])->value("project_chief");
                $comment[$k]['leader']  = empty($leader)?"":$leader;

                //查询项目
                $duty_person = Db::name("project_pro")->where(['id'=>$_POST['id']])->value("duty_person");
                $duty_person = explode(";",$duty_person);
                if(in_array($project_user['name'],$duty_person)){
                    $comment[$k]['reply_type'] = 1;
                }

                if(empty($v['images'])){
                    $comment[$k]['images']= [];
                }else{
                    $comment[$k]['images'] = explode(";",$v['images']);
                }
                //查看我回复的信息
                $reply = Db::name("project_pro_comment")->alias("a")
                    ->join("project_account c","a.add_id = c.id")
                    ->where(['a.pid'=>$v['id']])->field("a.content,a.addtime,a.images,c.name,a.add_id")->select();
                foreach ($reply as $k1=>$v1){
                    if(empty($v1['images'])){
                        $reply[$k1]['images'] = [];
                    }else{
                        $reply[$k1]['images'] = explode(';',$v1['images']);
                    }
                    $comment[$k]['reply_type'] = 2;
                }
                $comment[$k]['reply'] = $reply;

            }
            $black['list'] = $comment;
            $black['code'] = 0;
            $black['msg'] = "查询成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    /**
     * 获取形象进度
     */
    public function pro_figure(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            //形象进度
            $proWhere['pro_id'] = $_POST['id'];
            $figure = Db::name("project_pro_figure")->where($proWhere)->field("id,title,show_time,content,images,account_id")->order("id desc")->select();
            foreach ($figure as $k=>$v){
                if(empty($v['images'])){
                    $figure[$k]['images'] = [];
                }else{
                    $figure[$k]['images'] = explode(";",$v['images']);
                }
                //查询提交人
                $name = Db::name("project_account")->where(['id'=>$v['account_id']])->value("name");
                $figure[$k]['name'] = empty($name)?"管理员":$name;
                unset($figure[$k]['account_id']);

                $figure[$k]['show_time'] = date("Y-m-d",strtotime($v['show_time']));

            }

            //添加按钮展示权限
            $button = 0;
            $duty_person = Db::name("project_pro")->where(['id'=>$_POST['id']])->value("duty_person");
            $duty_person = explode(";",$duty_person);
            if(in_array($project_user['name'],$duty_person)){
                $button = 1;
            }
            $black['button'] = $button;
            $black['list'] = $figure;
            $black['code'] = 0;
            $black['msg'] = "查询成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    /**
     * 推进进度
     */
    public function pro_plan(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            $where['id'] = $_POST['id'];
            $duty_person = Db::name("project_pro")->where($where)->value("duty_person");

            $leading_cadre = 0;
            if(strpos($duty_person,$project_user['name'])!==false){
                $leading_cadre = 1;
            }

            //查询推进计划修改权限
            $config = Session::get("config");
            $configWhere['uniacid'] = $config['id'];;
            $planUpdate = $common->public_select("project_config",$configWhere)->value("planUpdate");
            $leading_cadre = ($planUpdate==1)?1:0;


            //形象进度
            $proWhere['pro_id'] = $_POST['id'];
            $year = Db::name("project_pro_plan")->where($proWhere)->field("plan_title")->group("plan_title")->order("plan_title desc")->select();
            $year = array_column($year,"plan_title");

            $year_value = [];
            foreach ($year as $v){
                $year_value[] = intval($v);
            }

            $proWhere['plan_title'] = empty($_POST['year'])?date("Y"):$_POST['year'];
            $figure = Db::name("project_pro_plan")->where($proWhere)->field("id,plan_title,plan_investment,plan_content,pro_id")->order("plan_title desc")->select();

            foreach ($figure as $k=>$v){
                $figure[$k]['desc'] =  $this->getplaintextintrofromhtml($v['plan_content'],100);
            }

            $black['list'] = $figure;
            $black['year'] = $year_value;
            $black['leading_cadre'] = $leading_cadre;
            $black['code'] = 0;
            $black['msg'] = "查询成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }



    function getplaintextintrofromhtml($html, $numchars) {
        // Remove the HTML tags
        $html = strip_tags($html);

        // Convert HTML entities to single characters
        $html = html_entity_decode($html, ENT_QUOTES, 'UTF-8');

        $html_len = mb_strlen($html,'UTF-8');
        // Make the string the desired number of characters
        // Note that substr is not good as it counts by bytes and not characters
        $html = mb_substr($html, 0, $numchars, 'UTF-8');

        // Add an elipsis
        if($html_len>$numchars)
        {
            $html .= "…";
        }
        return $html;
    }

    /**
     * 点评列表
     */
    public function commentlistApi(){
        $common = new Common();
//        $project_user = $common->testusername();
        $project_user = $this->iflogin();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }

        try{
            //查询我负责的项目
            $name = $project_user['name'];
            $read = empty($_POST['read'])?1:$_POST['read'];
            // or leader like '%".$name."%
            $pro_v1 = $this->conscientious($name);

            //查询我关联的项目
            $project_ids = $this->associated($project_user['id']);
            $pro_v = array_merge($pro_v1,$project_ids);

            //查询已读
            $where['pro_id'] = ['in',$pro_v];
            $where['read_id'] = $project_user['id'];
            $commentlog = Db::name("project_pro_comment_log")->where($where)->field("comment_id")->select();
            $commentlog = array_column($commentlog,"comment_id");

            $commentlog = empty($commentlog)?0:$commentlog;
            $type = ($read==1)?"not in":"in";
            $commentWhere['a.id'] = [$type,$commentlog];
            $commentWhere1['id'] = [$type,$commentlog];

            if(!empty($_POST['keyword'])){
                $commentWhere['b.name'] = ["like","%{$_POST['keyword']}%"];
            }

            //查询点评列表
            $commentWhere['a.pro_id'] = ['in',$pro_v];
            $commentWhere['a.add_id'] = ['neq',$project_user['id']];

            $comment = Db::name("project_pro_comment")->alias("a")
                ->join("project_account b","a.add_id = b.id")
                ->field("count(a.id) count,a.add_id,a.content,b.name,b.remark,a.addtime,b.fans_id,a.pro_id,a.type")
                ->where($commentWhere)->order("a.id desc")->group('a.add_id')->select();

            foreach ($comment as $k=>$v){

                //查询后台用户
                if($v['type'] == 1){
                    $comment[$k]['name'] = Db::name("account")->where(['id'=>$v['add_id']])->value("account");
                }


                //查询最近的消息
                $comment[$k]['content'] = Db::name("project_pro_comment")->where(['add_id'=>$v['add_id']])->order("id desc")->value("content");

                $commentWhere1['add_id'] = $v['add_id'];
                $addtime = Db::name("project_pro_comment")->where($commentWhere1)->order("id desc")->value("addtime");
                $comment[$k]['showtime'] = $addtime;
                $comment[$k]['addtime'] = strtotime($addtime)*1000;
                $avatar = Db::name("admin_fans")->where(['id'=>$v['fans_id']])->value("avatar");
                $comment[$k]['image'] = empty($avatar)?'':$avatar;
            }
            $black['bindremind'] = empty($project_user['fans_id'])?0:1;
            $black['list'] = $comment;
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    /**
     * 查看点评信息
     */
    public function lookOver(){
        $common = new Common();
//        $project_user = $common->testusername();

        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            $name = $project_user['name'];
            $add_id = $_POST['add_id'];
//            $add_id = 2;
            $pro_v1 = $this->conscientious($name);

            //查询我关联的项目
            $project_ids = $this->associated($project_user['id']);
            $pro_v = array_merge($pro_v1,$project_ids);

            //展示评论信息
            $commentWhere['a.pro_id'] = ['in',$pro_v];
            $commentWhere['a.add_id'] = $add_id;
//            $commentWhere['a.pid'] = 0;
            $list = Db::name("project_pro_comment")->alias("a")
                ->join("project_pro b","a.pro_id = b.id")
                ->join("project_account c","a.add_id = c.id")
                ->field("a.id,a.content,a.addtime,a.images,b.title,b.duty_unit,a.id,a.pro_id,c.name,a.pid,b.leader,a.add_id,b.project_chief,a.type")
                ->where($commentWhere)->order("a.id desc")->select();

            foreach ($list as $k=>$v){
                $data = [];
                //记录查看
                $data['comment_id'] = $v['id'];
                $data['pro_id'] = $v['pro_id'];
                $data['read_id'] = $project_user['id'];
                $log = Db::name("project_pro_comment_log")->where($data)->value('id');
                if(empty($log)){
                    $data['read_time'] = date("Y-m-d H:i:s",time());
                    Db::name("project_pro_comment_log")->insert($data);
                }
                //记录查看end
                if(!empty($v['pid'])){
                    $prentWhere['a.id'] = $v['pid'];
//                    $prentWhere['a.add_id'] = $project_user['id'];
                    $detail = Db::name("project_pro_comment")->alias("a")
                        ->join("project_pro b","a.pro_id = b.id")
                        ->join("project_account c","a.add_id = c.id")
                        ->field("a.id,a.content,a.addtime,a.images,b.title,b.duty_unit,a.id,a.pro_id,c.name,a.pid,b.leader,a.add_id,b.project_chief")->where($prentWhere)->find();

                    if(empty($detail)){
                        unset($list[$k]);
                    }else{
                        if(empty($detail['images'])){
                            $detail['images'] = [];
                        }else{
                            $detail['images'] = explode(';',$v['images']);
                        }
                        $list[$k] = $detail;
                        //查看回复的信息
                        $reply = Db::name("project_pro_comment")->alias("a")
                            ->join("project_account c","a.add_id = c.id")
                            ->where(['a.pid'=>$detail['id']])->field("a.content,a.addtime,a.images,c.name,a.add_id")->select();
                        foreach ($reply as $k1=>$v1){
                            if(empty($v1['images'])){
                                $reply[$k1]['images'] = [];
                            }else{
                                $reply[$k1]['images'] = explode(';',$v1['images']);
                            }
                        }
                        $list[$k]['reply_type'] = 2;
                        $list[$k]['reply'] = $reply;
                    }
                }else{
                    if(empty($v['images'])){
                        $list[$k]['images'] = [];
                    }else{
                        $list[$k]['images'] = explode(';',$v['images']);
                    }
                    $list[$k]['reply_type'] = 0;
                    if(in_array($v['pro_id'],$pro_v1)){
                        $list[$k]['reply_type'] = 1;
                    }
                    //查看我回复的信息
                    $reply = Db::name("project_pro_comment")->alias("a")
                        ->join("project_account c","a.add_id = c.id")
                        ->where(['a.pid'=>$v['id']])->field("a.content,a.addtime,a.images,c.name,a.add_id")->select();
                    foreach ($reply as $k1=>$v1){
                        if(empty($v1['images'])){
                            $reply[$k1]['images'] = [];
                        }else{
                            $reply[$k1]['images'] = explode(';',$v1['images']);
                        }
                        $list[$k]['reply_type'] = 2;
                        if($project_user['id']==$v1['add_id']){
                            $list[$k]['reply_type'] = 2;
                        }
                    }
                    $list[$k]['reply'] = $reply;
                }

                if($v['type'] == 1){
                    $list[$k]['name'] = Db::name("account")->where(['id'=>$v['add_id']])->value("account");
                }

            }

            $black['code'] = 0;
            $black['list'] = $list;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);

    }


    /**
     * 点评操作
     */
    public function commentApi(){
        $common = new Common();

        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        //$project_user = $common->testusername();
        try{

            //判断是否有点评权限
            $comment = Db::name("project_account")->where(['id'=>$project_user['id']])->value("comment");
            if($comment!=1){
                throw new Exception("暂无点评权限");
            }
            $data['pro_id'] = $pro_id = $_POST['pro_id'];

            //判断是否关联该项目
            $is_pro = Db::name("project_account_pro")->where(['account_id'=>$project_user['id'],'project_id'=>$pro_id])->value("id");
            if(empty($is_pro)){throw new Exception("你没有该项目的点评权限");}


//            $data['title'] = $_POST['title'];
            $data['content'] = $_POST['content'];
            if(!empty($_POST['images'])){
                $images = $_POST['images'];
                $data['images'] = $images;
            }
            $data['addtime'] = date("Y-m-d H:i:s",time());
            $data['add_id'] = $project_user['id'];
            $res = Db::name("project_pro_comment")->insertGetId($data);
            //更改项目点评状态
            Db::name("project_pro")->where(['id'=>$_POST['pro_id']])->update(['comment'=>1]);


            $notice = new Notice();
            $notice->sendMessage($project_user,$data);

            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    /**
     * 回复操作
     */
    public function reply(){
        $common = new Common();

        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
//            $id = $_POST['id'];
            $content = $_POST['content'];
            $id = $_POST['id'];
            //判断是否是该项目负责人
            $comment = Db::name("project_pro_comment")->field("id,pro_id,pid,add_id")->find($id);

            $duty_person = Db::name("project_pro")->where(['id'=>$comment['pro_id']])->value("duty_person");
            $duty_person = explode(";",$duty_person);
            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行回复操作");
            }

            $data['pro_id'] = $comment['pro_id'];
            $data['pid'] = $id;
            $data['content'] = $content;
            if(!empty($_POST['images'])){
                $images = $_POST['images'];
                $data['images'] = $images;
            }
            $data['addtime'] = date("Y-m-d H:i:s",time());
            $data['add_id'] = $project_user['id'];
            $res = Db::name("project_pro_comment")->insertGetId($data);

            //消息回复
            //获取openid
            $fans_id = Db::name("project_account")->where(['id'=>$comment['add_id']])->value('fans_id');
            if(!empty($fans_id)){
                $notice = new Notice();
                $notice->sendMessage($project_user,$data,$fans_id);
            }
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    /*
     * 添加形象进度
     */
    public function figure(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try {
            $id = $_POST['id'];
            //判断是否是该项目负责人
            $duty_person = Db::name("project_pro")->where(['id'=>$id])->value("duty_person");
            $duty_person = explode(";",$duty_person);
            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行操作");
            }
            $data['pro_id'] = $id;
            $data['title'] = $_POST['title'];
            $data['content'] = $_POST['content'];
            $data['show_time'] = date("Y-m-d 23:59:59",strtotime($_POST['show_time']));
            if(!empty($_POST['images'])){
                $images = $_POST['images'];
                $data['images'] = $images;
            }
            $data['addtime'] = date("Y-m-d H:i:s",time());
            $data['account_id'] = $project_user['id'];
            Db::name("project_pro_figure")->insert($data);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //更改进度
    public function schedule(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try {
            $id = $_POST['id'];
            //判断是否是该项目负责人
            $duty_person = Db::name("project_pro")->where(['id'=>$id])->value("duty_person");
            $duty_person = explode(";",$duty_person);
            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行操作");
            }
            //operation   1:增加  2:减少
            $operation = $_POST['operation'];
            $number = $_POST['number'];
            $schedule = $_POST['schedule'];
            //当前进度 progress  year_progress
            $scheduleVal = Db::name("project_pro")->where(['id'=>$id])->value($schedule);
            if($operation==1){
                $scheduleVal = $scheduleVal+$number;
                $scheduleVal = ($scheduleVal>100)?100:$scheduleVal;
            }else{
                $scheduleVal = $scheduleVal-$number;
                $scheduleVal = ($scheduleVal<0)?0:$scheduleVal;
            }
            Db::name("project_pro")->where(['id'=>$id])->update([$schedule=>$scheduleVal]);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //更改项目计划开工与竣工时间
    public function updatetimeApi(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try {

            $id = $_POST['id'];
            //判断是否是该项目负责人
            $duty_person = Db::name("project_pro")->where(['id'=>$id])->value("duty_person");
            $duty_person = explode(";",$duty_person);
            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行操作");
            }
            //onstream_time 开工时间   plan_complete_time 计划竣工时间
            $updatefield = $_POST['updatefield'];
            $updatetime = $_POST['updatetime'];
            Db::name("project_pro")->where(['id'=>$id])->update([$updatefield=>$updatetime]);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    //更新推进进度
    public function doplan(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try {
            $id = $_POST['pro_id'];
            //判断是否是该项目负责人
            $duty_person = Db::name("project_pro")->where(['id'=>$id])->value("duty_person");
            $duty_person = explode(";",$duty_person);
            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行操作");
            }
            $planid = $_POST['id'];
            //plan_investment 计划投资金额  plan_content 计划内容
            $updatefield = $_POST['updatefield'];
            $updatevalue = $_POST['updatevalue'];
            Db::name("project_pro_plan")->where(['id'=>$planid])->update([$updatefield=>$updatevalue]);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //新增推进进度
    public function addplan(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try {
            $id = $_POST['pro_id'];
            //判断是否是该项目负责人
            $duty_person = Db::name("project_pro")->where(['id'=>$id])->value("duty_person");
            $duty_person = explode(";",$duty_person);
            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行操作");
            }
            $data['pro_id'] = $id;
            $data['plan_title'] = $_POST['plan_title'];
            $data['plan_investment'] = $_POST['plan_investment'];
            $data['plan_content'] = $_POST['plan_content'];
            $data['addtime'] = date("Y-m-d H:i:s");
            $data['add_id'] = $project_user['id'];
            Db::name("project_pro_plan")->insert($data);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    //详细进度
    public function planList(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            $where['pro_id'] = $_POST['id'];
            $where['year'] =  $_POST['year'];


            $where1['id'] = $_POST['id'];
            $duty_person = Db::name("project_pro")->where($where1)->value("duty_person");
            $leading_cadre = 0;
            if(strpos($duty_person,$project_user['name'])!==false){
                $leading_cadre = 1;
            }
            $title = Db::name("project_pro")->where($where1)->value("title");


            $month = [1,2,3,4,5,6,7,8,9,10,11,12];
            $list = [];
            foreach ($month as $k=>$v){

                $where['month'] = $v;
                $detail = $common->public_select("project_pro_plandetail",$where,"year,month,advance_id,content,declare,images,declareTime")->find();
                if(empty($detail)){
                    $detail['year'] = $_POST['year'];
                    $detail['month'] = $v;
                    $detail['content'] = '-';
                    $detail['advance_id'] = '';
                }


                $detail['content'] = empty($detail['content'])?'':$detail['content'];
                $detail['declare'] = empty($detail['declare'])?'':$detail['declare'];
                $detail['declareTime'] = empty($detail['declareTime'])?'':$detail['declareTime'];
                $detail['images'] = empty($detail['images'])?'':$detail['images'];

                if(empty($detail['images'])){
                    $detail['images'] = [];
                }else{
                    $detail['images'] = explode(";",$detail['images']);
                }


                $list[$k] = $detail;
                //查询类别
                $advanceWhere['id'] = $detail['advance_id'];
                $advance = $common->public_select("project_advance",$advanceWhere)->value("name");
                $list[$k]['advance'] = empty($advance)?"-":$advance;
                $list[$k]['declareStatus'] = empty($detail['declare'])?"否":"是";

            }

            $advanceWhere1['status'] = 1;
            $advanceList = Db::name("project_advance")->where($advanceWhere1)->field("id,name")->select();

            $black['advanceList'] = $advanceList;
            $black['list'] = $list;
            $black['code'] = 0;
            $black['msg'] = "查询成功";
            $black['leading_cadre'] = $leading_cadre;
            $black['title'] = $title;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //详细进度新增&修改
    public function addPlanList(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            $id = $_POST['id'];
            //判断是否是该项目负责人
            $duty_person = Db::name("project_pro")->where(['id'=>$id])->value("duty_person");
            $duty_person = explode(";",$duty_person);
            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行操作");
            }
            $data['pro_id'] = $id;
            $data['year'] = $_POST['year'];
            $data['month'] = $_POST['month'];
            $plandetailId = Db::name("project_pro_plandetail")->where($data)->value("id");
            if(!empty($_POST['images'])){
                $images = $_POST['images'];
                $data['images'] = $images;
                $data['declare'] = $_POST['declare'];
                $data['declareTime'] = $_POST['declareTime'];
            }
            if(!empty($_POST['advance_id'])){
                $data['advance_id'] = $_POST['advance_id'];
            }
            if(!empty($_POST['content'])){
                $data['content'] = $_POST['content'];
            }

            $data['addtime'] = date("Y-m-d H:i:s",time());
            $data['add_id'] = $project_user['id'];

            if(empty($plandetailId)){
                Db::name("project_pro_plandetail")->insert($data);
            }else{
                $data['id'] = $plandetailId;
                Db::name("project_pro_plandetail")->update($data);
            }
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //详细精度内容
    public function planDetail(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            $where['pro_id'] = $_POST['id'];
            $where['year'] =  $_POST['year'];
            $where['month'] =  $_POST['month'];
            $detail = Db::name("project_pro_plandetail")->field("year,month,advance_id,content,declare,images,declareTime")->where($where)->find();

            if(empty($detail)){
                $detail['year'] = $_POST['year'];
                $detail['month'] = $_POST['month'];
                $detail['advance_id'] = '';
                $detail['content'] = '';
                $detail['declare'] = '';
                $detail['images'] = '';
                $detail['declareTime'] = '';
            }

            $black['data'] = $detail;
            $black['code'] = 0;
            $black['msg'] = "查询成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    //申报提交
    public function addDeclare(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try{
            $postDate = $_POST;
            $rule = [
                ["images", "require", "图片不能为空"],
                ["declare", "require", "内容不能为空"],
                ["declareTime", "require", "时间不能为空"],
            ];
            $validate = new Validate($rule);
            if (!$validate->check($postDate)) {
                throw new Exception($validate->getError());
            }
            $id = $_POST['id'];

            $year = $_POST['year'];
            $month = $_POST['month'];


            //判断是否是该项目负责人
            $duty_person = Db::name("project_pro")->where(['id'=>$id])->value("duty_person");
            $duty_person = explode(";",$duty_person);

            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行操作");
            }
            $data['pro_id'] = $id;
            $data['year'] = $year;
            $data['month'] = $month;
            $plandetailId = Db::name("project_pro_plandetail")->where($data)->value("id");

//            if(empty($plandetailId)){
//                throw new Exception("非法操作");
//            }

            $images = $_POST['images'];
            $data['images'] = $images;
            $data['declare'] = $_POST['declare'];
            $data['declareTime'] = $_POST['declareTime'];
            $data['update'] = date("Y-m-d H:i:s",time());
            $data['update_id'] = $project_user['id'];

            if(empty($plandetailId)){
                Db::name("project_pro_plandetail")->insert($data);
            }else{
                $data['id'] = $plandetailId;
                Db::name("project_pro_plandetail")->update($data);
            }

            $lastMonth = date('m', strtotime('-1 month'));  //上月
            $planYear = date("Y");
            $planMonth = $lastMonth;
            if($planYear==$year && $month==$planMonth){
                Db::name("project_pro")->where(['id'=>$id])->update(['project_status'=>0]);
            }



            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //获取推进类别
    public function advance(){
        try{
            $common = new Common();
            $appid = $_POST['appid'];
            $config = Db::name("config")->where(['xcx_appid' => $appid])->find();
            $where['uniacid'] = $config['id'];
            $where['status'] = 1;
            $list = $common->public_select("project_advance",$where,"id,name")->select();
            $black['code'] = 0;
            $black['list'] = $list;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    //查看固投情况
    public function fixedDetail(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try {
            $id = $_POST['pro_id'];
            //判断是否是该项目负责人
            $investment = Db::name("project_pro")->where(['id'=>$id])->value("investment");
            //查询该报表是否存在
            $detail = $common->public_select("project_pro_form",['pro_id'=>$id])->find();

            //已完成投资
            $arr = ['year_val','january_february','march','april','may','june','july','august','september','october','november','december'];
            $invested = 0;
            foreach ($arr as $item){
                if(!empty($detail[$item])){
                    $invested+=$detail[$item];
                }
            }

            $black['code'] = 0;
            $black['detail'] = empty($detail)?"":$detail;
            $black['invested'] = $invested;
            $black['percentage'] = round(($invested/$investment)*100,2);
            $black['investment'] = $investment;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //更新固投情况接口
    public function fixedApi(){
        $common = new Common();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $this->iflogin();
        }
        try {
            $id = $_POST['pro_id'];
            //判断是否是该项目负责人
            $duty_person = Db::name("project_pro")->where(['id'=>$id])->value("duty_person");
            $duty_person = explode(";",$duty_person);
            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行操作");
            }

            //查询该报表是否存在
            $data = $this->request->post();
            $detail_id = $common->public_select("project_pro_form",['pro_id'=>$id])->value("id");
            if(!empty($detail_id)){
                $data['id'] = $detail_id;
            }
            $common->handle("project_pro_form",$data);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


}